#include "tj_form_input.h"
#include "ui_tj_form_input.h"
#include "pub_var.h"

#include <QtDebug>
#include <QScroller>
#include <QMessageBox>
#include <QSqlError>
#include <QCheckBox>

Form_input::Form_input(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_input)
{
    ui->setupUi(this);

    //药品支出，输入检索信息，生成待选择品种列表
    md = new QSqlQueryModel();

    qr = new QSqlQuery(pub::db_o);
    qr0 = new QSqlQuery(pub::db_o);

    //补正途径标签页名称

    ui->tbMode->setTabText(0,"特批");
    ui->tbMode->setTabText(1,"邮寄");
    ui->tbMode->setTabText(2,"收费");
    ui->tbMode->setTabText(3,"补正");


    //
    //ui->tvList->setFont(this->font());
    //ui->lwList->setFont(this->font());

    //控制界面显示效果
    tmr = new QTimer;
    tmrItemDisplay = new QTimer;
    connect(tmr, SIGNAL(timeout()), this, SLOT(tmrTimeout()));
    connect(tmrItemDisplay, SIGNAL(timeout()), this, SLOT(tmrDisplayTimeout()));
    ui->toolBox->setCurrentIndex(0);
    //

    QSettings setIni("clin.ini", QSettings::IniFormat);
    //恢复当前窗口位置
    QRect rct = setIni.value("windowState/tempInput").toRect();
    this->setGeometry(rct);

    //批药领导
    QString sq = "select dic_value from drug_sub_dict where dic_type = 'leader'";
    ui->cbbLeader->clear();
    qr->exec(sq);
    while(qr->next()){
        ui->cbbLeader->addItem( qr->value(0).toString() );
    }

    //邮寄联系人列表, 最后联系过的30人
    ui->cbbReceiver->clear();
    sq = " select name from (select name from drug_post_address "
         " where type = 'post' order by oper_date desc) base "
         " where rownum <= 30 order by name";
    qr->exec(sq);

    while (qr->next()) {
        QString itm = qr->value(0).toString();
        ui->cbbReceiver->addItem( itm );
    }
    ui->cbbReceiver->setCurrentIndex(-1);

    //常用直接购药联系人, 最后联系过的30人
    ui->cbbPatientName->clear();
    sq = "select name from (select name from drug_post_address "
         " where type = 'patient' order by oper_date desc) where rownum <= 30 order by name";
    qr->exec(sq);
    while (qr->next()) {
        QString itm = qr->value(0).toString();
        ui->cbbPatientName->addItem( itm );
    }
    ui->cbbPatientName->setCurrentIndex(-1);

    current_item_name = "";//当前操作的项目名称
    respond_to_select_changed = true;   //对选择状态信号做响应

    //初始化界面状态
    on_toolBox_currentChanged(0);

    //ui->tbMode->setCurrentIndex(0);
    //QMessageBox::information(NULL,"note","test initialize");
}

Form_input::~Form_input()
{
    delete ui;
}

void Form_input::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/tempInput", QVariant(this->geometry()));

    emit destroyW( "iteminout" );

}

void Form_input::on_leSearch_textChanged(QString s)
{
    Q_UNUSED(s)
    tmr->start(300);
}

void Form_input::listItems(QString s)
{

    //显示符合检索要求的记录
    QString sq = "select p.TRADE_NAME drug_name, p.specs SPECS, "
                 "p.DRUG_CODE drug_code, p.PACK_UNIT PACK_UNIT,"
                 "p.PACK_QTY PACK_QTY, d.pym PYM, p.RETAIL_PRICE price, "
                 " nvl(d.recal, 0) RECAL, nvl(d.sub_account, 0) SUB_ACCOUNT"
                 " from pha_com_baseinfo p, drug_base_info d "
                 " where p.drug_code = d.drug_code and d.valid = '1'"
                 " and d.pym like '%" + s + "%' order by p.trade_name, specs";


    md->setQuery(sq, pub::db_o);

    md->setHeaderData(0, Qt::Horizontal, "品名");
    md->setHeaderData(1, Qt::Horizontal, "规格");

    ui->tvList->setModel(md);
    pub::setColumnWidth(ui->tvList, "0.6^0.3",ui->tvList->horizontalHeader()->width(),10 );

    //如果符合要求的记录只有一条，直接进行选中操作
    if( 1 == md->rowCount()){
        QModelIndex idx;
        idx = md->index(0, 0);//
        on_tvList_clicked(idx);
    }

}

void Form_input::on_tvList_clicked(const QModelIndex &index)
{
    //待选列表记录被单击选择
    mp.clear();
    mp["drug_name"] = index.siblingAtColumn(0).data(0).toString();
    mp["specs"] = index.siblingAtColumn(1).data(0).toString();
    mp["drug_code"] = index.siblingAtColumn(2).data(0).toString();
    mp["pack_unit"] = index.siblingAtColumn(3).data(0).toString();
    //mp["pack_qty"] = index.siblingAtColumn(4).data(0).toString();
    //mp["store_sum"] = index.siblingAtColumn(5).data(0).toString();
    mp["retail_price"] = index.siblingAtColumn(6).data(0).toString();
    //    mp["atinc"] = index.siblingAtColumn(7).data(0).toString();

    QString itm_txt = "";            //= mp["drug_name"] + "/" + mp["specs"] ;
    QString s = "select base.approve_info, company.fac_name"
                 " from pha_com_baseinfo base"
                 " left join pha_com_company company on company.fac_code = base.producer_code"
                 " where drug_code = '" + mp["drug_code"] + "'";

    qr0->exec(s);
    qr0->next();

    itm_txt += qr0->value(0).toString();  //"/" +
    itm_txt += "/" + qr0->value(1).toString();
    ui->leItem->setText( itm_txt );

    ui->leSum->setText("");
    ui->leSum->setEnabled(true);
    ui->leSum->setFocus();
}

void Form_input::on_tbAdd_clicked()
{
    //确认选中的记录数据
    ui->tbAdd->setEnabled(false);
    if(ui->leItem->text().isEmpty()){
        QMessageBox::warning(this,"注意", "未选定项目！");
        ui->tbAdd->setEnabled(true);
        return;
    }

    int n = ui->leSum->text().toInt();
    if( n <= 0){
        QMessageBox::warning(this,"注意", "数值数据无效！");
        ui->tbAdd->setEnabled(true);
        return;
    }

    //补全选中记录的数量和金额
    mp["apply_sum"] = ui->leSum->text();
    mp["amount"] = QString::number(mp["apply_sum"].toDouble() * mp["retail_price"].toDouble());
    //drugList << mp;


    //清空前一次检索
    ui->leSearch->setText("");
    ui->leSum->setText("");
    itemLength = ui->leItem->text().length();
    tmrItemDisplay->start(30);

    //重新计算已经输入的全部数据
    double amount = 0;
    //ui->lwList->clear();
    ui->lwList->clear();
    QMap < QString, QString > mp0;  //temp loop use
    bool duplicated = false;

    foreach (mp0, drugList) {

        if(mp0["drug_code"] == mp["drug_code"]  )
        {
            //记录重复
            duplicated = true;

            //移除原有记录

            drugList.removeOne(mp0);

            //累加两次记录
            int apply_num = mp0["apply_sum"].toInt() + mp["apply_sum"].toInt();
            double amount = mp0["amount"].toDouble() + mp["amount"].toDouble();

            mp0["apply_sum"] = QString::number(apply_num);
            mp0["amount"] = QString::number(amount);

            //累加结果重新保存
            drugList << mp0;
        }
        amount += mp0["amount"].toDouble();
        QString t;
        t.append(mp0["drug_name"]);
        t.append(" | ");
        t.append(mp0["specs"]);
        t.append(" | ");
        t.append(mp0["apply_sum"]);
        t.append(" | ");
        t.append(mp0["pack_unit"]);
        ui->lwList->addItem(t);

    }

    if(!duplicated)
    {
        //无重复，直接保存本次记录
        amount += mp["amount"].toDouble();
        QString t;
        t.append(mp["drug_name"]);
        t.append(" | ");
        t.append(mp["specs"]);
        t.append(" | ");
        t.append(mp["apply_sum"]);
        t.append(" | ");
        t.append(mp["pack_unit"]);
        ui->lwList->addItem(t);
        drugList<<mp;

    }

    ui->leAmount->setText(QString::asprintf("%.2f",amount));
    amountValue = ui->leAmount->text().toDouble()*100;
    ui->leSearch->setFocus();


}

void Form_input::on_pbClear_clicked()
{
    //重置录入状态
    drugList.clear();
    ui->lwList->clear();
    ui->teNote->clear();
    ui->teNoteSell->clear();
    //ui->pteAddress->clear();
    ui->cbbReceiver->setCurrentIndex(-1);
    ui->cbbPatientName->setCurrentIndex(-1);
    ui->pteTb1Memo->clear();
    ui->leSearch->setText("");
    ui->leItem->setText("");
    ui->leSum->setText("");
    ui->leSearch->setFocus();

    ui->leAmount->setText("");
    amountValue = 0;
}

void Form_input::clearDrugList()
{
    on_pbClear_clicked();
}


void Form_input::tmrDisplayTimeout()
{
    //品名显示的动态清除效果
    itemLength -- ;
    QString t = ui->leItem->text();
    t = t.mid(0, itemLength);
    ui->leItem->setText(t);
    if(itemLength <= 0){
        ui->leItem->setText("");
        tmrItemDisplay->stop();
        ui->tbAdd->setEnabled(true);
    }
}

void Form_input::tmrTimeout()
{
    tmr->stop();
    listItems(ui->leSearch->text().trimmed().toUpper());
}

void Form_input::on_tbExit_clicked()
{
    close();
}

void Form_input::on_pbSave_clicked()
{
    //数据保存

    if(drugList.isEmpty()){
        QMessageBox::warning(this,"注意", "未录入有效数据！");
        return;
    }

    QString sq;
    switch (ui->tbMode->currentIndex()) {
    case 0:{
        //outWay = "特批";

        inWay = "";
        if(ui->pteTb1Memo->toPlainText().isEmpty()){
            QMessageBox::information(this, "错误" , "备注内容不允许空白！");
            return;
        }

        if(!input("0")){
            return;
        }

        break;
    }
    case 1:{
        //QMessageBox::information(this, "note" ,"not finished");
        outWay = "邮寄";
        inWay = "";
        if(ui->cbbReceiver->currentText().isEmpty()
                || ui->lePhoneNo->text().isEmpty()
                || ui->pteAddress->toPlainText().isEmpty()){
            QMessageBox::information(this, "错误" , "不允许有空白项目！");
            return;
        }

        //drug_post_address表内容管理
        QString sq = "select name from drug_post_address where type = 'post' and name = '"
                + ui->cbbReceiver->currentText().trimmed() + "'";
        qr->exec(sq);
        if(!qr->next()){
            sq = "insert into drug_post_address (oper_date, type, name, phone, address) "
                 " values(sysdate, 'post','"
                    + ui->cbbReceiver->currentText().trimmed() + "','"
                    + ui->lePhoneNo->text().trimmed() + "','"
                    + ui->pteAddress->toPlainText().trimmed() + "')";
            qr->exec(sq);
        }
        else
        {
            sq = "update drug_post_address set "
                 " oper_date = sysdate, "
                 " phone = '%1', "
                 " address = '%2'"
                 " where type = 'post' and name = '%3'";
            sq = sq.arg(ui->lePhoneNo->text().trimmed())
                    .arg(ui->pteAddress->toPlainText().trimmed())
                    .arg(ui->cbbReceiver->currentText().trimmed());
            qr->exec(sq);

        }

        if(!input("1")){
            return;
        }
        break;
    }
    case 2:{

        outWay = "销售";
        inWay = "";

        inCash = ui->leInCash->text().toDouble()*100;
        inMM = ui->leInMM->text().toDouble()*100;
        outCash = ui->leOutCash->text().toDouble()*100;
        outMM = ui->leOutMM->text().toDouble()*100;

        if( outCash < 0 || outMM < 0 || inCash < 0 || inMM < 0 ){
            QMessageBox::information(this, "错误" , "数据关系不合理！");
            return;
        }


        if( outCash + outMM + amountValue != inCash + inMM){
            QMessageBox::information(this, "错误" , "数据关系不合理！");
            return;
        }

        //drug_post_address表内容管理
        QString sq = "select name from drug_post_address where type = 'patient' and name = '"
                + ui->cbbPatientName->currentText().trimmed() + "'";
        qr->exec(sq);
        if(!qr->next()){
            sq = "insert into drug_post_address (oper_date, type, name, phone, address)"
                 " values(sysdate, 'patient','"
                    + ui->cbbPatientName->currentText().trimmed() + "','','"
                    + ui->teNoteSell->toPlainText().trimmed() + "')";
            qr->exec(sq);
        }
        else
        {
            sq = "update drug_post_address set "
                 " oper_date = sysdate,"
                 " address = '%1'"
                 " where type = 'patient' and name = '%2'";
            sq = sq.arg(ui->teNoteSell->toPlainText().trimmed())
                    .arg(ui->cbbPatientName->currentText().trimmed());
            qr->exec(sq);
        }

        if(!input("2")){
            return;
        }

        break;
    }
    case 3:{
        //药品补正操作
        outWay = "";

        if(ui->radioButton->isChecked()){
            inWay = ui->radioButton->text();
        }else if(ui->radioButton_2->isChecked()){
            inWay = ui->radioButton_2->text();
        }else if(ui->radioButton_3->isChecked()){
            inWay = ui->radioButton_3->text();
//        }else if(ui->radioButton_4->isChecked()){
//            inWay = ui->radioButton_4->text();
        }else if(ui->radioButton_5->isChecked()){
            inWay = ui->radioButton_5->text();
        }else if(ui->radioButton_6->isChecked()){
            inWay = ui->radioButton_6->text();
        }
        if(!input("3")){
            return;
        }
        //QMessageBox::information(this, "note" ,"not complete");
        break;
    }
    }

    //all procedure is normal.
    emit clearDrugList();

    if(ui->tbMode->currentIndex() == 3)
    {
        //如最后进行的是补正操作，更新未补正列表
        listUnbalanced();
    }
    //    close();

    atinc_list.clear();//清除选定的列表
    ui->ckb_select_all->setChecked(false);
}

bool Form_input::input(QString mode)
{
    ui->pbSave->setEnabled(false);
    ui->pushButton->setEnabled(false);
    QString sq;

    QString ld = "";    //leader
    QString memo = "";
    if( "0" == mode)
    {   //特批
        if(ui->rb0->isChecked())
        {   //
            ld = ui->cbbLeader->currentText();
            outWay = ui->rb0->text();
        }
        else if(ui->rb1->isChecked())
        {   //
            //ld = ui->cbbLeader->currentText();
            outWay = ui->rb1->text();
        }
        else
        {
            //ld = ui->rb1->text();
            outWay = ui->rb2->text();
        }
        memo = ui->pteTb1Memo->toPlainText();
    }

    if( "1" == mode)
    {
        //邮寄
        memo = ui->cbbReceiver->currentText();
        memo.append("/");
        memo.append(ui->lePhoneNo->text());
        memo.append("/");
        memo.append(ui->pteAddress->toPlainText());
    }

    if( "2" == mode)
    {
        //零售
        memo = ui->cbbPatientName->currentText();
        memo.append("/");
        memo.append(ui->teNoteSell->toPlainText());

    }

    QString sum_str = "(";   //补正记负数，其它记正数. 括号为处理负数情况
    QString balancedStatus = "0";    //补正平衡标志，0未补正，1已补正
    if( "3" == mode)
    {
        //补正
        balancedStatus = "1";
        sum_str = " 0 - (";
        memo = ui->teNote->toPlainText();
    }

    sq = "select SEQ_DRUG_SUB_ACCOUNT.NEXTVAL as seq from dual";
    if(!qr->exec(sq))
    {
        QMessageBox::information(this, "错误" , "取序列号sql语句执行失败！");
        return false;
    }

    if(!qr->next())
    {
        QMessageBox::information(this, "错误" , "无法读取取序列号！");
        return false;

    }
    //groupNo , combine drug_sub_account to bill_rec if necessary.
    QString groupNo = qr->value(0).toString();
    //QMessageBox::information(this, "错误" , "序列号 : " + groupNo);

    pub::db_o.transaction();
    QSqlQuery *qr_tmp = new QSqlQuery(pub::db_o);

    foreach (mp, drugList)
    {
        sq = "select SEQ_DRUG_SUB_ACCOUNT.NEXTVAL as seq from dual";
        qr_tmp->exec(sq);
        qr_tmp->next();
        //groupNo , combine drug_sub_account to bill_rec if necessary.
        QString atinc = qr_tmp->value(0).toString();

        //oracle trigger 在插入成功之后修改 drub_base_info 的 recal 字段
        sq = "insert into drug_sub_account "
             "(balanced, drug_code, drug_name, oper_date, oper_sum, oper_name, leader, memo,"
             " out_way, in_way, synchronized, item_io_id, atinc)"
             " values('"
                + balancedStatus +
                + "','" + mp["drug_code"]
                + "','" + mp["drug_name"]
                + "', sysdate, "
                + sum_str + mp["apply_sum"]
                + "),'" + pub::usr_name
                + "','" + ld
                + "','" + memo
                + "','" + outWay
                + "','" + inWay
                + "','0','" + groupNo
                + "'," + atinc
                +") ";

        if(!qr_tmp->exec(sq)){
            QMessageBox::information(this, "错误" , "保存出入库记录错误：\n"
                                     + qr_tmp->lastError().text() + "\n"
                                     + qr_tmp->lastQuery());
            ui->pbSave->setEnabled(true);
            ui->pushButton->setEnabled(true);
            pub::db_o.rollback();
            delete qr_tmp;
            return false;
        }

        //如果是补正操作，对关联数据进行处理
        if( "3" == mode){   //补正
            sq = "update drug_sub_account set "
                 " bal_date = sysdate, "
                 " balanced = '1',bal_atinc = '"
                    + atinc
                    + "' where drug_code = '"
                    + mp["drug_code"]
                    + "' and atinc in (" + atincListStr + ")";

            qDebug()<<"补正操作，对关联数据进行处理:"<<sq<<"\n";
            if(!qr_tmp->exec(sq))
            {
                QMessageBox::information(this, "错误" , "保存补正关联记录错误：\n"
                                         + qr_tmp->lastError().text() + "\n"
                                         + qr_tmp->lastQuery());
                pub::db_o.rollback();
                delete qr_tmp;
                return false;
            }
        }
    }

    pub::db_o.commit();
    delete qr_tmp;

    if( "2" == mode){   //销售

        sq = "insert into bill_rec (item_io_id, cost, in_mmsg, in_cash, out_mmsg, out_cash, oper_name, synchronized)"
             " values ('" + groupNo + "', "
                + (ui->leAmount->text().isEmpty() ? "0" : ui->leAmount->text() ) + ","
                + (ui->leInMM->text().isEmpty() ? "0" : ui->leInMM->text() ) + ","
                + (ui->leInCash->text().isEmpty() ? "0" : ui->leInCash->text() ) + ","
                + (ui->leOutMM->text().isEmpty() ? "0" : ui->leOutMM->text() ) + ","
                + (ui->leOutCash->text().isEmpty() ? "0" : ui->leOutCash->text() ) + ",'"
                + pub::usr_name + "','0') ";

        if(!qr->exec(sq)){
            QMessageBox::information(this, "错误" , "保存收费数据错误：\n" + qr->lastError().text() + "\n" + qr->lastQuery());
            ui->pbSave->setEnabled(true);
            ui->pushButton->setEnabled(true);
            return false;
        }
    }

    ui->pbSave->setEnabled(true);
    ui->pushButton->setEnabled(true);
    return true;
}

void Form_input::on_tbInMM_clicked()
{
    //提取待支付金额
    ui->leInMM->setText(ui->leAmount->text());
    ui->leInCash->setText("");
    ui->leOutMM->setText("");
    ui->leOutCash->setText("");

}

void Form_input::on_tbInCash_clicked()
{
    //提取待支付金额
    ui->leInCash->setText(ui->leAmount->text());
    ui->leInMM->setText("");
    ui->leOutMM->setText("");
    ui->leOutCash->setText("");

}

void Form_input::on_tbOutCash_clicked()
{
    //计算找零金额
    ui->leOutMM->setText("");

    inMM = ui->leInMM->text().toDouble()*100;
    inCash = ui->leInCash->text().toDouble()*100;
    outCash = inMM + inCash - amountValue ;

    ui->leOutCash->setText(QString::asprintf("%.2f", double(outCash)/100));
}

void Form_input::on_tbOutMM_clicked()
{
    //计算找零金额
    ui->leOutCash->setText("");

    inMM = ui->leInMM->text().toDouble()*100;
    inCash = ui->leInCash->text().toDouble()*100;
    outMM = inMM + inCash - amountValue ;

    ui->leOutMM->setText(QString::asprintf("%.2f", double(outMM)/100));
}

void Form_input::on_toolButton_clicked()
{
    //撤销已录入的一条数据
    drugList.removeAt(listWidgetRowNum);
    ui->lwList->clear();

    //重新计算金额
    double amount = 0;
    foreach ( mp, drugList)
    {
        amount += mp["amount"].toDouble();
        QString t;
        t.append(mp["drug_name"]);
        t.append(" | ");
        t.append(mp["specs"]);
        t.append(" | ");
        t.append(mp["apply_sum"]);
        t.append(" | ");
        t.append(mp["pack_unit"]);

        ui->lwList->addItem(t);
    }

    ui->leAmount->setText(QString::asprintf("%.2f",amount));
    amountValue = ui->leAmount->text().toDouble()*100;

}

void Form_input::on_lwList_clicked(const QModelIndex &index)
{
    //记录待处理记录行序号，用于撤销单条记录
    listWidgetRowNum = index.row();
}

void Form_input::on_pushButton_clicked()
{
    close();
}

void Form_input::on_leSearch_returnPressed()
{

    listItems(ui->leSearch->text().trimmed().toUpper());

}

void Form_input::on_cbbPatientName_currentIndexChanged(const QString &arg1)
{
    //患者姓名选择变更

    ui->teNoteSell->clear();

    if(arg1.isEmpty())
    {
        return;
    }
    QString sq = "select name, address from drug_post_address where type = 'patient' and name = '" + arg1 + "'";
    qr0->exec(sq);
    qr0->next();

    ui->teNoteSell->append(qr0->value(1).toString());

}

void Form_input::on_cbbReceiver_currentIndexChanged(const QString &arg1)
{
    //邮寄联系人姓名选择变更
    ui->pteAddress->clear();
    ui->lePhoneNo->setText("");

    if(arg1.isEmpty())
    {
        return;
    }
    QString sq = "select name, phone, address "
                 " from drug_post_address "
                 " where type = 'post' and name = '" + arg1 + "'";
    qr0->exec(sq);
    qr0->next();
    ui->lePhoneNo->setText( qr0->value(1).toString() );
    ui->pteAddress->appendPlainText(qr0->value(2).toString());


}

void Form_input::on_leSum_returnPressed()
{
    on_tbAdd_clicked();
}

void Form_input::on_tbMode_currentChanged(int index)
{
    Q_UNUSED(index);
}

void Form_input::listUnbalanced(QString constrain)
{

    QString sq;
    ui->ckb_select_all->setChecked(false);

    qDebug()<<"constrain is "<<constrain;

    if(constrain.isEmpty())
    {
        //变更下拉列表
        sq = " select distinct drug_name"
             " from drug_sub_account "
             " where balanced = '0' and in_way is null"
             " order by drug_name";

        ui->cbDrugName->blockSignals(true);
        ui->cbDrugName->clear();
        ui->cbDrugName->addItem("");

        pub::fillCombo(ui->cbDrugName, sq, 0, qr, false);

        ui->cbDrugName->blockSignals(false);
    }

    //临时记账药品列表

    sq = "select drug_code, drug_name, oper_date, oper_sum, "
         "  (case when leader is not null "
         "   then concat(concat( leader,'，'), memo) "
         "   else memo end) 备注, "
         " atinc "
         " from drug_sub_account "
         " where balanced = '0' and in_way is null";
    if(!constrain.isEmpty())
    {
         sq.append(" and drug_name = '" + constrain + "'");
    }

    if(ui->rbDrugName->isChecked())
    {
        sq.append(" order by drug_name, oper_date");
    }
    else
    {
        sq.append(" order by oper_date,atinc");
    }

    qDebug()<<"药品列表："<<sq;

    qr0->exec(sq);

    //database driver do not surport size value, count this value.
    int rowCount = 0;
    while(qr0->next())
    {
        rowCount++;
    }

    if(rowCount == 0)
    {
        QMessageBox::information(this, "注意" , "未发现需要处理的数据！");
        return;
    }

    ui->twList->clear();

    ui->twList->setColumnCount(7);
    ui->twList->setRowCount(rowCount);

    QStringList titles;
    titles << "选择" << "品名" << "日期" << "数量" << "备注" << "drug_code" << "atinc";
    ui->twList->setHorizontalHeaderLabels(titles);

    int baseWidth = ui->twList->width();
    pub::setColumnWidth(ui->twList, "0.08^0.22^0.2^0.1^0.3^0^0^0", baseWidth,10 );

    qr0->first();

    int row = 0;
    while(row < rowCount)
    {
        //ui->twList->insertRow(row);

        QWidget *wgt;
        QHBoxLayout *lot;
        QCheckBox *ckbx;

        //checkBox
        wgt = new QWidget();
        lot = new QHBoxLayout();
        ckbx = new QCheckBox();
        lot->setMargin(1);
        lot->addWidget(ckbx, 0 ,Qt::AlignCenter);
        wgt->setLayout(lot);
        ui->twList->setCellWidget(row, 0, wgt);

        if(atincListStr.indexOf(qr0->value(5).toString()) > -1)
        {
            ckbx->setChecked(true);
        }

        connect(ckbx, &QCheckBox::clicked, this, &Form_input::listCheckBoxChanged);

        //drug_name
        ui->twList->setItem(row,1,new QTableWidgetItem(qr0->value(1).toString()));
        //oper_date
        ui->twList->setItem(row,2,new QTableWidgetItem(qr0->value(2).toDate().toString("yyyy-MM-dd")));
        //oper_sum
        ui->twList->setItem(row,3,new QTableWidgetItem(qr0->value(3).toString()));
        //memo
        ui->twList->setItem(row,4,new QTableWidgetItem(qr0->value(4).toString()));
        //drug_code
        ui->twList->setItem(row,5,new QTableWidgetItem(qr0->value(0).toString()));
        //atinc
        ui->twList->setItem(row,6,new QTableWidgetItem(qr0->value(5).toString()));

        row++;
        qr0->next();
    }


}

void Form_input::on_toolBox_currentChanged(int index)
{
    //支出或补正状态变更
    if(index == 0)
    {
        ui->tbMode->setCurrentIndex(0);
        ui->tbMode->setTabEnabled(0, true);
        ui->tbMode->setTabEnabled(1, true);
        ui->tbMode->setTabEnabled(2, true);
        ui->tbMode->setTabEnabled(3, false);
        ui->pbClear->setEnabled(true);
        ui->toolButton->setEnabled(true);
        emit clearDrugList();
        atinc_list.clear();//清除选定的列表

    }
    else
    {
        ui->tbMode->setCurrentIndex(3);
        ui->tbMode->setTabEnabled(0, false);
        ui->tbMode->setTabEnabled(1, false);
        ui->tbMode->setTabEnabled(2, false);
        ui->tbMode->setTabEnabled(3, true);
        ui->pbClear->setEnabled(false);
        ui->toolButton->setEnabled(false);
        emit clearDrugList();
        atinc_list.clear();//清除选定的列表
        listUnbalanced();
    }
}

void Form_input::listCheckBoxChanged()
{

    //列表中的选中状态发生变化

    if(!respond_to_select_changed)
    {
        //当前不需要对状态做响应
        return;
    }

    //clear previous display
    clearDrugList();

    //if(current_item_name.isEmpty())
   // {
     //   qDebug()<<"current_item_name is NULL";
       // return;
    //}

    //移除列表中指定的项目名称
    //remove_from_list(current_item_name);

    //save checked atinc_list
    int rows = ui->twList->rowCount();

    QWidget *wgt;
    QHBoxLayout * lot;
    QCheckBox *ckbx;
    //QStringList atincList;

    for(int i = 0; i< rows; i++)
    {
        wgt = ui->twList->cellWidget(i,0);
        lot = qobject_cast<QHBoxLayout * > (wgt->layout());
        ckbx = qobject_cast<QCheckBox *>(lot->itemAt(0)->widget());

        QString atinc = ui->twList->item(i, 6)->text();
//        QString atinc = ui->twList->item(i, 6)->text();

        if(ckbx->isChecked())
        {
            atinc_list << atinc;
            //atinc_item_name.insert(atinc,"");
        }
        else
        {
            atinc_list.remove(atinc);
            //atinc_item_name.remove(atinc);
        }

    }

    if(atinc_list.size() == 0)
    {
        //no drug is checked.
        return;
    }

    atincListStr = "";

    foreach(QString s, atinc_list)
    {
        if(!atincListStr.isEmpty())
        {
            //if temp string is not empty, add a comma.
            atincListStr.append(",");
        }
        atincListStr.append("'");
        atincListStr.append(s);
        atincListStr.append("'");
    }

    QString sq ;

    sq = "select a.drug_code, a.drug_name,b.specs, "
         " sum(a.oper_sum) sum, b.pack_unit, b.retail_price "
         " from drug_sub_account a, pha_com_baseinfo b "
         " where a.drug_code = b.drug_code and a.atinc in ("
            + atincListStr
            +") group by a.drug_code, a.drug_name,b.specs, b.pack_unit, b.retail_price ";

    double amount = 0;

    ui->lwList->clear();

    qr0->exec(sq);

    while(qr0->next())
    {
        mp.clear();
        mp["drug_name"] = qr0->value(1).toString();
        mp["specs"] = qr0->value(2).toString();
        mp["drug_code"] = qr0->value(0).toString();
        mp["pack_unit"] = qr0->value(4).toString();
        //mp["pack_qty"] = index.siblingAtColumn(4).data(0).toString();
        //mp["store_sum"] = index.siblingAtColumn(5).data(0).toString();
        mp["retail_price"] = qr0->value(5).toString();;

        mp["apply_sum"] = qr0->value(3).toString();
        mp["amount"] = QString::number(mp["apply_sum"].toDouble() * mp["retail_price"].toDouble());

        drugList<<mp;

        amount += mp["amount"].toDouble();

        QString t;
        t.append(mp["drug_name"]);
        t.append(" | ");
        t.append(mp["specs"]);
        t.append(" | ");
        t.append(mp["apply_sum"]);
        t.append(" | ");
        t.append(mp["pack_unit"]);

        ui->lwList->addItem(t);
    }
    ui->leAmount->setText(QString::asprintf("%.2f",amount));
    amountValue = ui->leAmount->text().toDouble()*100;
    //ui->leSearch->setFocus();
}

void Form_input::on_rbDrugName_toggled(bool checked)
{
    //待补正数据排列方式变更，按品名
    if(checked)
    {
        //clearDrugList();
        //listUnbalanced();
        ui->twList->sortByColumn(1,Qt::AscendingOrder);
    }

}

void Form_input::on_rbOperDate_toggled(bool checked)
{
    //待补正数据排列方式变更，按录入日期
    if(checked)
    {
        //clearDrugList();
        //listUnbalanced();
        ui->twList->sortByColumn(2,Qt::AscendingOrder);
    }

}


void Form_input::on_cbDrugName_currentIndexChanged(const QString &arg1)
{
    listUnbalanced(arg1);
    qDebug()<<"arg is "<<arg1;
}

void Form_input::remove_from_list(QString item_name)
{
    //撤销指定名称的项目

    ui->lwList->clear();

    //重新计算金额
    double amount = 0;
    int idx = 0;
    int idx_remove = -1;
    foreach ( mp, drugList) {

        if(mp["drug_name"] == item_name)
        {
            idx_remove = idx;
            continue;
            //drugList.removeAt(idx);
        }
        idx++;

        amount += mp["amount"].toDouble();
        QString t;
        t.append(mp["drug_name"]);
        t.append(" | ");
        t.append(mp["specs"]);
        t.append(" | ");
        t.append(mp["apply_sum"]);
        t.append(" | ");
        t.append(mp["pack_unit"]);

        ui->lwList->addItem(t);
    }

    if(idx_remove > -1)
    {
        drugList.removeAt(idx);
    }

    ui->leAmount->setText(QString::asprintf("%.2f",amount));
    amountValue = ui->leAmount->text().toDouble()*100;
}

void Form_input::on_twList_clicked(const QModelIndex &index)
{
    current_item_name = index.siblingAtColumn(1).data().toString();
}

void Form_input::on_ckb_select_all_clicked()
{

    respond_to_select_changed = false;
    int rows = ui->twList->rowCount();

    QWidget *wgt;
    QHBoxLayout * lot;
    QCheckBox *ckbx;

    bool check_status = ui->ckb_select_all->isChecked();

    for(int i = 0; i< rows; i++)
    {
        wgt = ui->twList->cellWidget(i,0);
        lot = qobject_cast<QHBoxLayout * > (wgt->layout());
        ckbx = qobject_cast<QCheckBox *>(lot->itemAt(0)->widget());

        QString atinc = ui->twList->item(i, 6)->text();

        ckbx->setChecked(check_status);

    }

    respond_to_select_changed = true;

    //current_item_name = ui->cbDrugName->currentText().isEmpty();

    listCheckBoxChanged();
}
